#include <iostream>
#include <string>
#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <unordered_map>

using std::cout;
using std::endl;
using std::string;
using std::unordered_map;
using namespace muduo::net;

class DictServer
{

public:
    DictServer(short port)
        : _server(&_loop, InetAddress(port), "DictServer", muduo::net::TcpServer::Option::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&DictServer::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&DictServer::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        // 一个 I/O 线程，一个 work 线程
        _server.setThreadNum(2);
    }

    void start()
    {
        _server.start();

        cout << "SERVER START SUCCESS...\n";
        _loop.loop();
    }

private:
    void onConnection(const TcpConnectionPtr &ptr)
    {
        cout << ptr.get() << " CONNECTION ";
        cout << (ptr->connected() ? "UP" : "DOWN") << endl;
    }

    void onMessage(const TcpConnectionPtr &ptr, Buffer *buf, muduo::Timestamp timestamp)
    {
        string msg = buf->retrieveAllAsString();
        if (msg.back() == '\n')
            msg.pop_back();

        string ret = translate(msg);

        ptr->send(ret);
    }

    string translate(string &msg)
    {
        static unordered_map<string, string> map = {
            {"hello", "你好"},
            {"world", "世界"},
            {"你好", "hello"},
            {"世界", "world"}
        };

        auto iter = map.find(msg);
        if (iter == map.end())
            return "NoDict";

        return iter->second;
    }

private:
    EventLoop _loop;
    TcpServer _server;
};

int main(int args, char *argv[])
{
    DictServer server(9090);
    server.start();

    return 0;
}